// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/profiles/profile_theme_update_service.h"

#include "base/notreached.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_attributes_entry.h"
#include "chrome/browser/profiles/profile_attributes_storage.h"
#include "chrome/browser/themes/theme_properties.h"
#include "chrome/browser/themes/theme_service.h"
#include "chrome/browser/themes/theme_service_factory.h"
#include "chrome/browser/ui/signin/profile_colors_util.h"
#include "chrome/common/themes/autogenerated_theme_util.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_source.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/base/theme_provider.h"

ProfileThemeUpdateService::ProfileThemeUpdateService(
    Profile* profile,
    ProfileAttributesStorage* profile_attributes_storage,
    ThemeService* theme_service)
    : profile_(profile),
      profile_attributes_storage_(profile_attributes_storage),
      theme_service_(theme_service) {
  theme_service_->AddObserver(this);
  // Kicks off an update on startup.
  UpdateProfileThemeColors();
}

ProfileThemeUpdateService::~ProfileThemeUpdateService() {
  theme_service_->RemoveObserver(this);
}

void ProfileThemeUpdateService::UpdateProfileThemeColors() {
  ProfileAttributesEntry* entry =
      profile_attributes_storage_->GetProfileAttributesWithPath(
          profile_->GetPath());
  if (!entry)
    return;

  if (!theme_service_->UsingAutogeneratedTheme()) {
    // Only save colors for autogenerated themes.
    entry->SetProfileThemeColors(absl::nullopt);
    return;
  }

  ThemeService* service = ThemeServiceFactory::GetForProfile(profile_);
  ProfileThemeColors colors =
      GetProfileThemeColorsForThemeSupplier(service->GetThemeSupplier());
  entry->SetProfileThemeColors(colors);
}

void ProfileThemeUpdateService::OnThemeChanged() {
  UpdateProfileThemeColors();
}
